import { api } from "./api";
import { fillShopName } from "./shop";

export async function getAdmMembers(body, user) {
  if (!user.role || user.role == 5) {
    throw "无权限";
  }
  if (user.sid) {
    body.sid = user.sid;
  }
  body._data = 1;
  const data = await api.getMembers(body);
  data.rows = data.rows.filter((it) => {
    return it.role > user.role;
  });
  if (user.role == 1) {
    await fillShopName(data.rows);
  }
  return data;
}

export async function getMemberInfo(body, user) {
  if (!user.role) {
    throw "无权限";
  }
  const row = await api.getMember(body.id || 0);
  if (!row) {
    throw "记录不存在";
  }
  if (user.sid && row.sid != user.sid) {
    throw "无权限";
  }
  return row;
}

export async function postMember(body, user) {
  if (!user.role || user.role > 3) {
    throw "无权限";
  }
  if (body.role && user.role >= body.role) {
    throw "无权限";
  }
  if (user.sid) {
    body.sid = user.sid;
  }
  let member;
  let mpUid;
  if (body.id > 0) {
    member = await api.getMember(body.id);
    if (!member) throw "管理员信息不存在";
    mpUid = member.userId;
    if (member.role == user.role && member.userId != user.id) {
      throw "同级成员，暂无修改权限";
    }
  } else {
    member = await api.getMember({
      sid: body.sid,
      mobile: body.mobile,
      role: body.role,
    });
    if (member) throw "管理员已存在：" + body.mobile;
  }
  if (body.mobile) {
    const mpUser = await api.getUserInfo({
      mobile: body.mobile,
    });
    if (!mpUser) {
      throw "手机号未在小程序中登录过：" + body.mobile;
    }
    mpUid = mpUser.id;
    await api.postUserInfo({
      id: mpUid,
      status: 3,
    });
  }

  body.userId = mpUid;
  return api.postMember(body);
}
